package com.scalar.forecast.forecastEntry.actionCommands;

import com.scalar.forecast.actionCommands.ActionCommand;
import com.scalar.forecast.forecastEntry.forms.ForecastEntrySearchForm;
import com.scalar.forecast.forecastEntry.dao.ForecastEntrySearchDAO;
import com.scalar.forecast.forecastEntry.SearchFieldListComparator;
import com.scalar.forecast.forecastEntry.SearchField;
import com.scalar.forecast.commons.SessionKeys;
import com.scalar.forecast.forecastSetup.ForecastTimeFrame;
import com.scalar.forecast.forecastSetup.dao.ForecastSetupDAO;

import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Calendar;

/**
 * User: Sujan Kumar
 * Date: Feb 21, 2005
 * Time: 4:56:21 PM
 */
public class ForecastEntrySearchBuildCommand extends ActionCommand
{
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    {
        ForecastEntrySearchForm forecastEntrySearchForm = ( ForecastEntrySearchForm ) form;
        String doSearch = request.getParameter ( "search" );
        if ( forecastEntrySearchForm == null )
        {
            forecastEntrySearchForm = new ForecastEntrySearchForm();
        }
        HashMap errors = new HashMap ();
        HashMap info = new HashMap ();
        //forecastEntrySearchForm.setYear( now.get ( Calendar.YEAR ) );
        ArrayList searchFieldList = new ArrayList();
        ArrayList forecastSetupFields = null;
        try
        {
            forecastSetupFields = ForecastSetupDAO.getForecastSetupFields(null);
            if ( doSearch == null || !"true".equalsIgnoreCase( doSearch.trim() ) )
            {
                forecastEntrySearchForm.setOrderBy( ForecastEntrySearchNewCommand.getDefaultOrderBy ( forecastSetupFields ) );
            }
            request.setAttribute ( "forecastSetupFields", forecastSetupFields );
        }
        catch ( ScalarException e )
        {
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_COULD_NOT_LOAD_FORECAST_SETUP_FIELDS );
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
            System.out.println ( "----------exception in search new Command:" );
            e.printStackTrace();
            return mapping.findForward ( "errorPage" );
        }
        try
        {
            searchFieldList = ForecastEntrySearchDAO.getForecastSetupSearchFields(null);
            int searchFieldListSize = searchFieldList.size();
            SearchField searchField = null;
            //for not to display showNext in the searchfield
            for ( int i=0; i < searchFieldListSize; i++ )
            {
                searchField = ( SearchField )searchFieldList.get( i );
                if ( "showNext".equalsIgnoreCase( searchField.getName() ) )
                {
                    searchField.setDisplay( false );
                    break;
                }
                if ( "startMonth_Quarter_Year".equalsIgnoreCase( searchField.getPropertyName() ) )
                {
                    String displayName = searchField.getDisplayName();
                    int startIndex = displayName.indexOf( "Start" );
                    if ( startIndex >= 0 )
                    {
                        displayName = displayName.substring( startIndex+5 );
                        searchField.setDisplayName( displayName );
                    }
                }
            }
            ForecastEntrySearchNewCommand.loadSearchFieldListPropertyValues(forecastEntrySearchForm,searchFieldList);
            //adding new Fields to the search screen
            searchField = new SearchField();
            searchField.setName( "salesPersonId" );
            searchField.setSortOrder( 8 );
            searchField.setDisplayName ( "Sales Person" );
            searchField.setType ( "select" );
            searchField.setDisplay( true );
            searchField.setPropertyName( "salesPersonId" );
            LabelValueBean labelValueBean = new LabelValueBean( "---Select SalesPerson---","-1");
            ArrayList propValues = new ArrayList();
            propValues = ForecastEntrySearchDAO.getAllForecastSalesPersons( null );
            propValues.add (0, labelValueBean );
            searchField.setPropertyValues( propValues );

            searchFieldList.add ( searchField );

            searchField = new SearchField();
            searchField.setName( "buildNo" );
            searchField.setSortOrder( 9 );
            searchField.setDisplayName ( "Build Number" );
            searchField.setType ( "text" );
            searchField.setDisplay( true );
            searchField.setPropertyName( "buildNo" );
            searchFieldList.add ( searchField );

        }
        catch ( Exception e )
        {
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_COULD_NOT_LOAD_SEARCH_FIELDS );
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
            System.out.println ( "----------exception in search new Command:" );
            e.printStackTrace();
            return mapping.findForward ( "errorPage" );
        }
        ForecastEntrySearchNewCommand.setSortOrder ( forecastEntrySearchForm.getOrderBy(), searchFieldList );
        Collections.sort( searchFieldList, new SearchFieldListComparator() );
        forecastEntrySearchForm.setSearchFieldList( searchFieldList );


        request.setAttribute ( "showBuildNumbers", "false" ); //request field used to display search results
        if ( doSearch != null && "true".equalsIgnoreCase( doSearch.trim() ) )
        {
            try
            {
                ArrayList buildNumbers = new ArrayList();
                buildNumbers = ForecastEntrySearchDAO.getBuildNumbers ( null, forecastEntrySearchForm );
                if ( buildNumbers == null || ( buildNumbers != null && buildNumbers.size() == 0 ) )
                {
                    errors.put( INFO_SEARCH_NO_RESULT , null );
                    request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
                }
                else
                {
                    request.setAttribute ( "buildNumbers", buildNumbers );
                    request.setAttribute ( "showBuildNumbers", "true" );
                }
            }
            catch ( ScalarException e )
            {
                System.out.println ( "----Could Not Get Search Results----" );
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_COULD_NOT_LOAD_SEARCH_RESULTS );
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
            }
        }
        else
        {
            try
            {
                Calendar  now = Calendar.getInstance();
                ForecastTimeFrame timeframe = ForecastSetupDAO.getForecastTimeFrame(null);
                //this request field is used to display the label after the showNext textfield.
                if ( "Month".equalsIgnoreCase( timeframe.getTfName() ) )
                {
                    forecastEntrySearchForm.setStartMonth_Quarter_Year( now.get( Calendar.MONTH ) );
                }
                else if ( "Quarter".equalsIgnoreCase( timeframe.getTfName() ) )
                {
                    int currentQuarter = -1;
                    try
                    {
                        currentQuarter = ForecastEntrySearchDAO.getCurrentQuarter(null);
                    }
                    catch ( Exception e)
                    {
                        System.out.println ( "--Exception in getting the current Quarter---" );
                        e.printStackTrace();
                    }
                    forecastEntrySearchForm.setStartMonth_Quarter_Year( currentQuarter );
                }
                else if ( "Year".equalsIgnoreCase( timeframe.getTfName() ) )
                {
                    forecastEntrySearchForm.setStartMonth_Quarter_Year( now.get( Calendar.YEAR ) );
                }
            }
            catch ( Exception e )
            {
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_COULD_NOT_LOAD_FORECAST_TIMEFRAME );
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
                System.out.println ( "----------exception while getting the timeframe-----");
                e.printStackTrace();
                return mapping.findForward ( "errorPage" );
            }
        }
        ActionForward actionForward = mapping.findForward ( "searchBuildPage" );
        return actionForward;
    }
}
